<template>
	<uni-nav-bar :title="`购物袋(${dataList.length || 0})`" height="100rpx" fixed />
	<view class="cart-container">
		<view class="goods-detail">
			<!-- 滚动组件 -->
			<f-scroll-list
				:status="loadMore.status"
				:showIcon="loadMore.showIcon"
				:color="loadMore.color"
				:contentText="loadMore.contentText"
				:useLoadMore="dataList.length > 0 ? true : false"
			>
				<f-cart-singleGoods-card
					@delSucceed="delSucceed"
					@currentItemInfo="currentItemInfo"
					@handleChange="handleChange"
					@changeNumber="changeNumber"
					@handleSeclectChange="handleSeclectChange"
				/>
			</f-scroll-list>
			<view class="submit-bar-box" v-if="dataList.length > 0">
				<!-- 提交打样单 -->
				<f-cart-submitBar @posterShare="onPosterShare" @printOrder="onPrintOrder" />
			</view>
		</view>
		<!-- 海报分享弹窗 -->
		<f-poster-shareModal
			v-if="show"
			ref="posterShareRef"
			:Data="selectedItems"
			:qrCode="qrCode"
			:shareCode="shareCode"
			@cancel="cancelPoster"
		/>

		<!-- 打样提醒弹窗 -->
		<uni-popup ref="popup" type="dialog" class="my-popup">
			<uni-popup-dialog
				type="info"
				mode="base"
				title="确认提交打样申请"
				confirmText="确认"
				:duration="2000"
				:before-close="true"
				@close="close"
				@confirm="printConfirm"
			>
				<view class="text">打样申请提交后将会计入部门费用，提交后不可撤销，请确认！</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import { ref, reactive, computed } from 'vue';
	import sheep from '@/sheep';
	import { onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
	import cartApi from './../../sheep/api/cart.js';
	import printRecordApi from './../../sheep/api/printRecord.js';
	import _ from 'lodash';
	import QRCode from 'qrcode';

	// 加载状态
	const loadMore = reactive({
		status: '',
		showIcon: true,
		color: '',
		contentText: {},
	});
	const qrCode = ref('');
	const shareCode = ref('');
	const show = ref(false);
	const popup = ref();
	const dataList = computed(() => sheep.$store('cart').list);
	const selectedItems = computed(() => sheep.$store('cart').selectedItems);

	/**
	 * 每次进入页面都会加载
	 */
	onShow(() => {
		getDataList();
	});
	const selectCount = ref(0);
	const selectText = ref('');
	const currentItemId = ref(0);
	const currentItemList = ref([]);
	//更新购物车//当前点击的商品项
	const currentItemInfo = (item) => {
		currentItemList.value = [...item.printTypes];
		selectCount.value = item.count;
		currentItemId.value = item.id;
	};
	//下拉列表的change事件
	const handleSeclectChange = (val) => {
		currentItemList.value.forEach((item) => {
			if (val === item.value) {
				selectText.value = item.value;
			} else {
				selectText.value = '';
			}
		});
		updateCartInfo();
	};
	//点击数量的change事件
	const changeNumber = (val, item) => {
		selectCount.value = val;
		currentItemId.value = item.id; //商品ID
		selectText.value = item.printType; //规格尺寸
		updateCartInfo();
	};

	const updateCartInfo = () => {
		let data = {
			id: currentItemId.value,
			count: selectCount.value,
			printType: selectText.value,
		};
		cartApi.updateCart(data).then((res) => {
			sheep.$store('cart').update(res.data.cartItems);
			uni.showToast({
				title: '购物车更新成功',
				icon: 'success',
				mask: true,
				duration: '500',
			});
		});
	};
	/**
	 * 拿列表数据
	 * @param {string} val 加载类型，'0'-上拉加载，'1'-下拉刷新
	 */
	const getDataList = () => {
		sheep.$store('cart').getList();
	};
	/**
	 * 提交购物车(提交预订单)
	 */
	const commitCartList = (data) => {
		return new Promise((resolve) => {
			printRecordApi.submitPrintPre(data).then((res) => {
				resolve(res);
			});
		});
	};
	/*
	 * 提交打样单确定事件
	 */
	const printConfirm = () => {
		//提交打样单之前，需要先提交调预订单接口
		let data = {
			cartItemArgsList: selectedItems.value,
		};
		commitCartList(data)
			.then((res) => {
				if (!res.data.id) {
					//如果后期增加了清理失效商品，应不会触发该逻辑
					return uni.showToast({
						title: res.data.errorMessage,
						icon: 'error',
						mask: true,
					});
				}
				let info = {
					id: res.data.id,
					distributionMode: 1,
					shippingAddressId: 1,
					selfPickUpSiteId: 1,
					consigneeId: 1,
					source: 2,
				};
				//提交打样单列表
				printRecordApi
					.submitPrint(info)
					.then((res) => {
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							mask: true,
						});
						setTimeout(() => {
							getDataList();
						}, 200);
					})
					.finally(() => {
						popup.value.close();
					});
			})
			.finally(() => {
				popup.value.close();
			});
	};
	/**
	 * 删除单品成功回调事件
	 */
	const delSucceed = async () => {
		getDataList();
		sheep.$store('cart').allSelectedChange(false); // 删除后重置全选状态
	};
	/**
	 * 点击分享按钮事件
	 */
	const onPosterShare = (e) => {
		if (selectedItems.value.length == 0) {
			return uni.showToast({
				title: '请至少勾选一个商品进行分享哦',
				icon: 'error',
				mask: true,
			});
		}
		if (selectedItems.value.length > 5) {
			return uni.showToast({
				title: '每次最多分享5个商品哦',
				icon: 'error',
				mask: true,
			});
		}
		uni.hideTabBar({
			success: () => {
				show.value = e;
				getQRCode();
			},
		}); //隐藏底部导航栏
	};
	/**
	 * 获取二维码和分享码
	 */
	const getQRCode = () => {
		let data = {
			imageItems: dealWithDataList(selectedItems.value),
		};
		cartApi.getShareQrCode(data).then((res) => {
			// 生成二维码
			QRCode.toDataURL(res.data?.qrCode)
				.then((url) => {
					console.log(url);
					qrCode.value = url || '';
				})
				.catch((err) => {
					console.error(err);
				});
			shareCode.value = res.data?.no || '';
		});
	};
	/**
	 * 分享数据处理
	 */
	const dealWithDataList = (list) => {
		return list.map((item) => {
			return {
				imageId: item.imageId,
				printType: item.printType,
			};
		});
	};
	/**
	 * 分享modal关闭事件
	 */
	const cancelPoster = () => {
		show.value = false;
		uni.showTabBar(); //恢复底部导航栏
	};
	/**
	 * 提交打样单事件
	 */
	const onPrintOrder = () => {
		if (selectedItems.value == 0) {
			return sheep.$helper.toast('请先选择打样商品');
		} else {
			popup.value.open();
		}
	};
	/**
	 * popup 关闭事件
	 */
	const close = () => {
		popup.value.close();
	};
	/**
	 * reachBottom 上拉加载
	 */
	onReachBottom(() => {
		loadMore.status = 'no-more';
	});
	/**
	 * 下拉刷新
	 */
	onPullDownRefresh(async () => {
		uni.showLoading({
			title: '正在刷新...',
			mask: true,
		});
		getDataList();
		setTimeout(function () {
			uni.stopPullDownRefresh();
			uni.hideLoading();
		}, 500);
	});
</script>

<style scoped lang="scss">
	.cart-container {
		height: 100%;
		.submit-bar-box {
		}
		.goods-detail {
			padding-bottom: 200rpx;
			overflow: hidden;
			:deep(.uni-scroll-view) {
				overflow: visible !important;
			}
		}
		.my-popup {
			.text {
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
			}
		}
	}
	:deep(.uni-popup-dialog) {
		border-radius: 32rpx;
	}
	:deep(.uni-popup__info) {
		color: #111111;
	}
	.dialog {
		border: 1px solid red;
		box-sizing: border-box;
	}
</style>
